<template>
  <div class="uploadImg-container">
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <!-- v-if v-else 有图片显示图片没有显示图标 -->
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>

<script>
// 腾讯云账号与密码
// SecretId: AKIDEG2XmkRqyqQjlWzB5LK1RZR2MPCiwta0
// SecretKey: 91cwzlFSO2PVKr76pGQItDF0UhdHekZ7
export default {
  data() {
    return {
      imageUrl: ''
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      // 下面的代码是固定写法
      const COS = require('cos-js-sdk-v5')
      // 填写自己腾讯云cos中的key和id (密钥)
      const cos = new COS({
        SecretId: 'AKIDEG2XmkRqyqQjlWzB5LK1RZR2MPCiwta0', // 身份识别ID
        SecretKey: '91cwzlFSO2PVKr76pGQItDF0UhdHekZ7' // 身份秘钥
      })
      // 执行上传操作
      cos.putObject({
        Bucket: 'zzj-1307943183', /* 存储桶 */
        Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
        Key: res.file.name, /* 文件名 */
        StorageClass: 'STANDARD', // 上传模式, 标准模式
        Body: res.file // 上传文件对象
      }, (err, data) => {
        console.log(err, data)
      })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式或者png格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style scoped lang="scss">
.uploadImg-container {
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
